Component({
  properties: {
    // 初始颜色值
    color: {
      type: String,
      value: '#000000'
    },
    // 组件标题
    title: {
      type: String,
      value: '选择颜色'
    },
    // 是否显示预设颜色
    showPresets: {
      type: Boolean,
      value: true
    }
  },

  data: {
    visible: false,
    // 预设颜色列表
    presetColors: [
      '#000000', '#FFFFFF', '#FF0000', '#00FF00', '#0000FF',
      '#FFFF00', '#FF00FF', '#00FFFF', '#808080', '#800000',
      '#808000', '#008000', '#800080', '#008080', '#000080'
    ],
    // RGB 值
    red: 0,
    green: 0,
    blue: 0,
    hexColor: '#000000',
    tempColor: '#000000'
  },

  lifetimes: {
    attached() {
      // 组件初始化时将传入的颜色值解析为 RGB
      this.setData({
        hexColor: this.properties.color,
        tempColor: this.properties.color
      });
      this.hexToRgb(this.properties.color);
    }
  },

  methods: {
    // 打开取色器
    open() {
      this.setData({
        visible: true,
        tempColor: this.data.hexColor
      });
    },

    // 关闭取色器
    close() {
      this.setData({
        visible: false
      });
    },

    // 确认选择
    confirm() {
      const color = this.data.tempColor;
      this.setData({
        hexColor: color,
        visible: false
      });
      // 触发事件通知外部
      this.triggerEvent('change', { color });
    },

    // 取消选择
    cancel() {
      this.setData({
        visible: false
      });
    },

    // 16进制颜色转 RGB
    hexToRgb(hex: string) {
      hex = hex.replace(/^#/, '');
      if (hex.length === 3) {
        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
      }
      const num = parseInt(hex, 16);
      const red = (num >> 16) & 255;
      const green = (num >> 8) & 255;
      const blue = num & 255;
      
      this.setData({
        red,
        green,
        blue
      });
    },

    // RGB 转 16进制颜色
    rgbToHex() {
      const { red, green, blue } = this.data;
      const hexColor = '#' + 
        ((1 << 24) + (red << 16) + (green << 8) + blue)
          .toString(16)
          .slice(1)
          .toUpperCase();
      
      this.setData({
        tempColor: hexColor
      });
    },

    // 当红色滑块值改变
    onRedChange(e: WechatMiniprogram.SliderChange) {
      this.setData({
        red: e.detail.value
      });
      this.rgbToHex();
    },

    // 当绿色滑块值改变
    onGreenChange(e: WechatMiniprogram.SliderChange) {
      this.setData({
        green: e.detail.value
      });
      this.rgbToHex();
    },

    // 当蓝色滑块值改变
    onBlueChange(e: WechatMiniprogram.SliderChange) {
      this.setData({
        blue: e.detail.value
      });
      this.rgbToHex();
    },

    // 选择预设颜色
    selectPresetColor(e: WechatMiniprogram.TouchEvent) {
      const { color } = e.currentTarget.dataset;
      this.setData({
        tempColor: color
      });
      this.hexToRgb(color);
    },

    // 阻止冒泡，防止点击内容区域时关闭弹窗
    preventClose() {
      return;
    }
  }
}); 